﻿/* Includes: */
#include "GraphEngine.h"
#include "CreekGen.h"

/** Глобальный флаг индикации того, что игра приостановлена */
static bool g_gamePaused = false;
TCreek *g_creekTest = NULL;

/** Таг для добавления слоя подтверждения завершения игры. */
#define GAME_BREAK_CONFIRM_TAG  ( 321 )

void createCreek()
{
    if ( g_creekTest ) {
        delete g_creekTest;
    }
    g_creekTest = new TCreek;

    // инициализация параметров ручья (описаны в комментариях в описании класса, см. CreekGen.h)
    g_creekTest->screenWidth = 800;
    g_creekTest->xLeftBegin = g_creekTest->screenWidth / 4;
    g_creekTest->xRightBegin = g_creekTest->screenWidth * 3 / 4;
    g_creekTest->creekLength = 10000;
    g_creekTest->bankStep = g_creekTest->screenWidth / 20;
    g_creekTest->minCreekWidth = g_creekTest->screenWidth / 4;
    g_creekTest->maxCreekWidth = g_creekTest->screenWidth * 3 / 4;
    g_creekTest->isCreekCyclic = false;
    g_creekTest->itemsCountUnderWater = g_creekTest->creekLength / 1000;
    g_creekTest->itemsCountOnWater = g_creekTest->itemsCountUnderWater;
    g_creekTest->itemsCountOverWater = g_creekTest->itemsCountUnderWater;
    g_creekTest->frame.isCreekCyclic = g_creekTest->isCreekCyclic;
    g_creekTest->delta = 5;
    g_creekTest->frame.width = g_creekTest->screenWidth;
    g_creekTest->frame.height = 480;
    g_creekTest->frame.up = g_creekTest->frame.height;
    g_creekTest->frame.down = 0;

    // генерируем каркасные точки ручья
    g_creekTest->buildBankCurves();
    // строим интерполированный берег (в виде прямоугольников) между каркасными точками №2 и №7
    g_creekTest->fillBankCurves(0, 20);
    // теперь у объекта creek есть два заполненных описаниями прямоугольников
    // вектора - leftRectangleBank и rightRectangleBank
}

// on "init" you need to initialize your instance
GrGameLayer::GrGameLayer()
{
    /* 1. В начале вызовим статический метод инициализации слоя. */
    if ( ! CCLayer::init() ) {
        return;
    }

    bool ret = false;

    do {
        /////////////////////////////
        // 2. add a menu item with "X" image, which is clicked to quit the program
        //    you may modify it.

        // add a "close" icon to exit the progress. it's an autorelease object
        /*CCMenuItemImage *pCloseItem = CCMenuItemImage::itemFromNormalImage(
                                            "CloseNormal.png",
                                            "CloseSelected.png",
                                            this,
                                            menu_selector( GrGameLayer::menuCloseCallback ) );
        CC_BREAK_IF(! pCloseItem);

        pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );

        // create menu, it's an autorelease object
        CCMenu* pMenu = CCMenu::menuWithItems(pCloseItem, NULL);
        CC_BREAK_IF(! pMenu);

        pMenu->setPosition( CCPointZero );
        this->addChild( pMenu, 1);*/

        /////////////////////////////
        // 3. add your codes below...

        // add a label shows "Hello World"
        // create and initialize a label
        CCLabelTTF* pLabel = CCLabelTTF::labelWithString("Brook", "Arial", 24);
        // ask director the window size
        CCSize size = CCDirector::sharedDirector()->getWinSize();

        // position the label on the center of the screen
        pLabel->setPosition( ccp(size.width / 2, size.height - 50) );

        // add the label as a child to this layer
        this->addChild(pLabel, 2);

        // add "HelloWorld" splash screen"
        //CCSprite* pSprite = CCSprite::spriteWithFile("HelloWorld.png");

        // position the sprite on the center of the screen
        //pSprite->setPosition( ccp(size.width/2, size.height/2) );

        // add the sprite as a child to this layer
        // this->addChild(pSprite, 0);

        /* Добавляем картинку заставки. */
        //CCSprite* sprite = CCSprite::spriteWithFile( "CreekBack.png" );

        /* Помещаем картинку заставки в центр окна. */
        //sprite->setPosition( ccp( size.width/2, size.height/2 ) );

        // add the sprite as a child to this layer
        //this->addChild( sprite, 1 );

        //this->schedule( schedule_selector(GrGameScene::gameLogic), 1.0 );
        this->setIsTouchEnabled( true );
        //this->schedule( schedule_selector( GrGameScene::updateGame ) );

        ret = true;
    } while( 0 );
}

void GrGameLayer::onEnter()
{
    createCreek();

    schedule( schedule_selector( GrGameLayer::updateScene ) );
}

void GrGameLayer::draw()
{
    CCLayer::draw();

    /* Нарисуем прямоугольники границ ручья. */
    /* цикл по всем прямоугольникам */
    CCPoint vertices[5];
    for ( unsigned int i = 0; i < g_creekTest->leftRectangleBank.size(); ++i )  {
        /* Зеленый левый берег. */
	    glColor4ub( 55, 198, 0, 255 );
	    /* glColor4f(1.0, 1.0, 0.0, 1.0); */
	    glLineWidth( 1 );
	    vertices[0] = CCPointMake( g_creekTest->leftRectangleBank.at(i).v1.x,
                                   g_creekTest->leftRectangleBank.at(i).v1.y );
        vertices[1] = CCPointMake( g_creekTest->leftRectangleBank.at(i).v2.x,
                                   g_creekTest->leftRectangleBank.at(i).v2.y );
        vertices[2] = CCPointMake( g_creekTest->leftRectangleBank.at(i).v3.x,
                                   g_creekTest->leftRectangleBank.at(i).v3.y );
        vertices[3] = CCPointMake( g_creekTest->leftRectangleBank.at(i).v4.x,
                                   g_creekTest->leftRectangleBank.at(i).v4.y ); 
        vertices[4] = CCPointMake( g_creekTest->leftRectangleBank.at(i).v1.x,
                                   g_creekTest->leftRectangleBank.at(i).v1.y );
 
	    ccDrawPoly( vertices, 5, false);
    }
    for ( int i = 0; i < g_creekTest->rightRectangleBank.size(); ++i )  {
        /* Зеленый правый берег. */
	    glColor4ub( 55, 198, 0, 255 );
	    /*glColor4f(1.0, 1.0, 0.0, 1.0); */
	    glLineWidth( 1 );
	    vertices[0] = CCPointMake( g_creekTest->rightRectangleBank.at(i).v1.x,
                                   g_creekTest->rightRectangleBank.at(i).v1.y );
        vertices[1] = CCPointMake( g_creekTest->rightRectangleBank.at(i).v2.x,
                                   g_creekTest->rightRectangleBank.at(i).v2.y );
        vertices[2] = CCPointMake( g_creekTest->rightRectangleBank.at(i).v3.x,
                                   g_creekTest->rightRectangleBank.at(i).v3.y );
        vertices[3] = CCPointMake( g_creekTest->rightRectangleBank.at(i).v4.x,
                                   g_creekTest->rightRectangleBank.at(i).v4.y ); 
	    vertices[4] = CCPointMake( g_creekTest->rightRectangleBank.at(i).v1.x,
                                   g_creekTest->rightRectangleBank.at(i).v1.y );

        ccDrawPoly( vertices, 5, false );
    }
}

GrGameLayer::~GrGameLayer()
{
    if ( g_creekTest ) {
        delete g_creekTest;
        g_creekTest = NULL;
    }
}

void GrGameLayer::updateScene( ccTime delta )
{
    if ( ! g_gamePaused ) {
        /* TODO: Обновление информации игровой сцены. */

    }
}

GrGameScene::GrGameScene( bool showMenuBtn )
    : GrSceneAbstract( showMenuBtn )
{
}

void GrGameScene::prepareScene()
{
    /* добавим кнопку или строку для возврата в главное меню. */
    CCLabelTTF* label = CCLabelTTF::labelWithString( "Main Menu", "Arial", 20 );
    CCMenuItemLabel* pMenuItem = CCMenuItemLabel::itemWithLabel( label, this, 
                                        menu_selector( GrSceneAbstract::mainMenuCallback ) );

    CCMenu* pMenu = CCMenu::menuWithItems( pMenuItem, NULL );
    CCSize s = CCDirector::sharedDirector()->getWinSize();
    pMenu->setPosition( CCPointZero );
    pMenuItem->setPosition( CCPointMake( s.width - 50, 25 ) );

    addChild( pMenu, 1 );
}

void GrGameScene::runScene()
{
    CCLayer* layer = new GrGameLayer();
    this->addChild( layer );
    layer->release();

    CCDirector::sharedDirector()->replaceScene( 
                    GE_MAKE_SCENE_TRANSACTION( SCENE_TRANSITION_DURATION, this ) );
}

void GrGameScene::mainMenu()
{
    if ( ! g_gamePaused ) {
        CCSize s = CCDirector::sharedDirector()->getWinSize();
        CCSize newSize = CCSizeMake( s.width / 2, s.height / 2 );
        CCLayer* layer = new GrBreakGameConfirmLayer( newSize );
        layer->autorelease();
        layer->setContentSize( newSize );
        layer->setPosition( newSize.width / 2, newSize.height / 2 );

        this->addChild( layer, 1, GAME_BREAK_CONFIRM_TAG );
        g_gamePaused = true;
    }
}

GrBreakGameConfirmLayer::GrBreakGameConfirmLayer( CCSize &size )
{
    initWithColor( ccc4( 255, 214, 91, 128 ) );
    CCSize s = size;//CCDirector::sharedDirector()->getWinSize();

    CCLabelTTF* label = CCLabelTTF::labelWithString( "ARE YOU SURE?", "Arial", 32);
    label->setPosition( CCPointMake( s.width / 2, s.height - 50));
    label->setColor( ccc3( 80, 140, 60 ) );
    addChild(label);

    CCMenu *pMenu = CCMenu::menuWithItems(NULL);
    pMenu->setPosition( CCPointZero );
	label = CCLabelTTF::labelWithString( "Yes", "Arial", 32);
    CCMenuItemLabel* pMenuItem1 = CCMenuItemLabel::itemWithLabel( label, this, 
                                    menu_selector( GrBreakGameConfirmLayer::onYesCallback ) );
    pMenuItem1->setPosition( CCPointMake( s.width / 2 - 50, s.height / 2 ) );
	pMenu->addChild(pMenuItem1, 1);
	
    label = CCLabelTTF::labelWithString( "No", "Arial", 32);
	CCMenuItemLabel* pMenuItem2 = CCMenuItemLabel::itemWithLabel( label, this, 
                                    menu_selector( GrBreakGameConfirmLayer::onNoCallback ) );
	pMenuItem2->setPosition( CCPointMake( s.width / 2 + 50, s.height / 2 ) );
	pMenu->addChild(pMenuItem2, 2);
    
    addChild(pMenu);
}

GrBreakGameConfirmLayer::~GrBreakGameConfirmLayer()
{
}

void GrBreakGameConfirmLayer::onYesCallback( CCObject* pSender )
{
    g_gamePaused = false;
    GE_SHOW_MAIN_MENU;
}

void GrBreakGameConfirmLayer::onNoCallback( CCObject* pSender )
{
    g_gamePaused = false;
    CCScene* activeScene = CCDirector::sharedDirector()->getRunningScene();
    activeScene->removeChildByTag( GAME_BREAK_CONFIRM_TAG, true );
}